#include "ClientHandler.h"

ClientHandler::ClientHandler() {
	pthread_mutex_init(&ch_mutex, NULL);
	userProfileManager = UserProfileManager::getInstance();
	responses = false;
}

ClientHandler::~ClientHandler() {
	pthread_mutex_destroy(&ch_mutex);
	delete userProfileManager;
}

Message ClientHandler::parse_request(const string& strmessage) {
	try {
		return MessageParser::parseRequestMessage(strmessage);
	} catch (ParsingException &ex) {
		Log::warning(ex.what());
		return Message();
	}
}

string ClientHandler::parse_response(const multimap<string, string>& message) {
	if (message.empty())
		return "";
	try {
		return MessageParser::parseResponseMessage(message);
	} catch (ParsingException& ex) {
		Log::warning(ex.what());
		return "";
	}
}

void ClientHandler::push_request(const string& mac, const string& message) {
	request_messages.push(make_pair(mac, message));
}

pair<string, string> ClientHandler::pop_response() {
	pthread_mutex_lock(&ch_mutex);
	pair<string, string> response = response_messages.front();
	response_messages.pop();
	responses = !response_messages.empty();
	pthread_mutex_unlock(&ch_mutex);

	return response;
}

void ClientHandler::proccess_requests() {
	pthread_mutex_lock(&ch_mutex);
	while (!request_messages.empty()) {
		string response;
		Message msg = parse_request(request_messages.front().second);
		if (msg.messageType == REQUEST_LIST)
			response = parse_response(cf.getTopNList(
					request_messages.front().first, msg.list_length));
		else if (msg.messageType == SUBMIT_RATING)
			userProfileManager->updateUserProfile(
					request_messages.front().first, msg.rating.first,
					msg.rating.second);
		else if (msg.messageType == REQUEST_PROFILE)
			response = parse_response(multimap<string, string> ());
		response_messages.push(make_pair(request_messages.front().first,
				response));
		request_messages.pop();
		responses = true;
	}
	pthread_mutex_unlock(&ch_mutex);
}
